var GM = google.maps, GMEVENT = google.maps.event, GMCP = google.maps.ControlPosition, GMOT = google.maps.drawing.OverlayType;

/*****************************************************************************************************************************/
function MVCArrayBinder(mvcArray) {
	this.array_ = mvcArray;
}

MVCArrayBinder.prototype = new google.maps.MVCObject();

MVCArrayBinder.prototype.get = function(key) {
	if (!isNaN(parseInt(key))) {
		return this.array_.getAt(parseInt(key));
	} else {
		this.array_.get(key);
	}
}

MVCArrayBinder.prototype.set = function(key, val) {
	if (!isNaN(parseInt(key))) {
		this.array_.setAt(parseInt(key), val);
	} else {
		this.array_.set(key, val);
	}
}
/**************************************************************************************************************************/
function CoordMapType(tileSize) {
	this.tileSize = tileSize;
}

CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
	var div = ownerDocument.createElement('div');
	div.innerHTML = coord;
	div.style.width = this.tileSize.width + 'px';
	div.style.height = this.tileSize.height + 'px';
	div.style.fontSize = '10';
	div.style.borderStyle = 'solid';
	div.style.borderWidth = '1px';
	div.style.borderColor = '#AAAAAA';
	return div;
};

/*******************************************************************************************************************/

DM.log = function(str) {

	$("#log").html(str)

}
/**************************************************************************************************************************/

DM.gismap = function(options) {// 创建对象

	var _this = {}, that = {};

	_this.config = {

		mapOpt : $.extend({//地图参数
			zoom : 17,
			disableDoubleClickZoom : true,
			draggable : true,
			center : new GM.LatLng(22.827, 108.334), //南宁
			mapTypeId : GM.MapTypeId.ROADMAP,
			disableDefaultUI : true,
			zoomControl : true,
			draggableCursor : "default",
			styles : gmap_style || []
		}, options || {}),

		polylineOpt : {

			path : {//绘图轨迹参数
				strokeOpacity : 0,
				icons : [{
					icon : {
						path : 'M 0,-1 0,1',
						strokeOpacity : 1,
						scale : 2,
						strokeColor : "blue"
					},
					offset : '0',
					repeat : '10px'
				}]
			},
			jkx : {//架空线参数
				strokeColor : "#FF0000",
				strokeOpacity : 1.0,
				strokeWeight : 2,
				icons : []
			},
			fzx : {//辅助线属性参数
				strokeColor : "#2200CC",
				strokeOpacity : 1.0,
				strokeWeight : 2,
				icons : []
			},
			hover : {//hover时样式
				strokeColor : "#000",
				strokeOpacity : 1.0,
				strokeWeight : 4,
				icons : []
			},
			dl : {
				strokeOpacity : 0,

				icons : [{
					icon : {
						path : 'M 0,-1 0,1',
						strokeOpacity : 1,
						strokeWeight : 1,
						scale : 2,
						strokeColor : "#FF0000"
					},
					offset : '0',
					repeat : '10px',
				}]

			}

		},
		markersImages : {

			pathPoint : new GM.MarkerImage("img/markers.fw.png", new GM.Size(13, 13), new GM.Point(8, 9), new GM.Point(6, 6)), //轨迹点
			pathPointSelect : new GM.MarkerImage("img/markers.fw.png", new GM.Size(13, 13), new GM.Point(41, 9), new GM.Point(6, 6)), //选中的轨迹点
			kgx : new GM.MarkerImage("img/markers.fw.png", new GM.Size(64, 64), new GM.Point(0, 32), new GM.Point(32, 32)), //开关箱
			fjx : new GM.MarkerImage("img/markers.fw.png", new GM.Size(64, 64), new GM.Point(0, 160), new GM.Point(32, 32)), //分接箱
			dg8 : new GM.MarkerImage("img/markers.fw.png", new GM.Size(32, 32), new GM.Point(240, 0), new GM.Point(16, 16)), //电杆8
			dg10 : new GM.MarkerImage("img/markers.fw.png", new GM.Size(32, 32), new GM.Point(272, 0), new GM.Point(16, 16)), //电杆10
			dg12 : new GM.MarkerImage("img/markers.fw.png", new GM.Size(32, 32), new GM.Point(304, 0), new GM.Point(16, 16)), //电杆12
			dg15 : new GM.MarkerImage("img/markers.fw.png", new GM.Size(32, 32), new GM.Point(336, 0), new GM.Point(16, 16)), //电杆15
			hd : new GM.MarkerImage("img/markers.fw.png", new GM.Size(32, 32), new GM.Point(368, 0), new GM.Point(16, 16)), //横担
			dlt : new GM.MarkerImage("img/markers.fw.png", new GM.Size(13, 13), new GM.Point(10, 235), new GM.Point(6, 6))//电缆头
		},

		action : {
			"select" : "select", //选择
			"path" : "path", //绘制路径
			"kgx" : "kgx", //低压开关箱
			"fjx" : "fjx", //分接箱
			"around" : "around", //沿轨迹布设备及电缆,
			"jkx" : "jkx", //架空线
			"dl" : "dl", //电缆
			"dlt" : "dlt", //电缆头
			"dg8" : "dg8", //电杆8
			"dg10" : "dg10", //电杆10
			"dg12" : "dg12", //电杆12
			"dg15" : "dg15", //电杆15
			"hd" : "hd", //横担
			"fzx" : "fzx"//辅助线
		},

		url : {

			"kgx" : "device/kgx.html",
			"fjx" : "device/fjx.html",
			"jkx" : "device/jkx.html",
			"dl" : "device/dl.html"
		},

		overlayType : {//添加图层类型

		}

	}

	_this.map = null;
	//地图

	_this.mgr = null;
	//标注管理器

	_this.drawingManager = null;
	//绘图管理器

	//绘图动作
	_this.action = null

	_this.DB = TAFFY();
	//临时存储TAFFY对象

	_this.temMarkerDB = TAFFY();
	//临时存放连线marker
	//{id:*,index:*}

	_this.markerDB = TAFFY();
	//存储所有marker
	//{id : m__gm_id,line : *,index : *,type:*,obj:*,label:*}

	_this.polylineDB = TAFFY();
	//存储所有polyline
	//{id : m__gm_id,type:*,obj:*}

	_this.temPolylineDB = TAFFY();
	//存储临时路径
	// {id : m.__gm_id,obj : *}

	/**************************************************************************************************************************/
	//创建地图
	_this.loadMap = function(container) {

		_this.map = new GM.Map(container, _this.config.mapOpt);

		_this.map.overlayMapTypes.insertAt(0, new CoordMapType(new google.maps.Size(256, 256)));

		_this.mgr = new MarkerManager(_this.map);

		return _this.map;
	}
	//绑定地图事件
	_this.mapEvent = function() {

		GMEVENT.addListener(_this.map, "click", function(e) {

			if (_this.getDrawAction() == _this.config.action.path) {

				_this.drawPath(e)

			}

		})
	}
	//绑定marker事件
	_this.markerEvent = function(marker) {

		GMEVENT.addListener(marker, "click", function(e) {

			if (_this.getDrawAction() == _this.config.action.path) {

				_this.drawPath(e, marker, "m")

			}

		})
	}
	//polyline 事件

	_this.polylineEvent = function(polyline) {

		GMEVENT.addListener(polyline, "click", function(e) {

			if (_this.getDrawAction() == _this.config.action.path) {

				_this.drawPath(e, polyline, "p")

			}

		})

		GMEVENT.addListener(polyline, "mouseover", function(e) {

			if (_this.getDrawAction() == _this.config.action.path) {

				_this.polylineOnPathMouseOver(polyline)

			}

		})
		GMEVENT.addListener(polyline, "mouseout", function(e) {

			if (_this.getDrawAction() == _this.config.action.path) {

				_this.polylineOnPathMouseOut(polyline)

			}

		})
	}

	_this.polylineOnPathMouseOver = function(polyline) {

		if (polyline.type == _this.config.action.path) {
			return false;
		}

		polyline.set("icons", _this.config.polylineOpt.hover.icons)

		polyline.set("strokeColor", _this.config.polylineOpt.hover.strokeColor)

		polyline.set("strokeOpacity", _this.config.polylineOpt.hover.strokeOpacity)

		polyline.set("strokeWeight", _this.config.polylineOpt.hover.strokeWeight)

	}

	_this.polylineOnPathMouseOut = function(polyline) {

		if (polyline.type == _this.config.action.path) {
			return false;
		}

		polyline.set("icons", _this.config.polylineOpt[polyline.type].icons)

		polyline.set("strokeColor", _this.config.polylineOpt[polyline.type].strokeColor)

		polyline.set("strokeOpacity", _this.config.polylineOpt[polyline.type].strokeOpacity)

		polyline.set("strokeWeight", _this.config.polylineOpt[polyline.type].strokeWeight)

	}
	/**************************************************************************************************************************/

	//存储marker
	_this.saveMarkerToDB = function(opt) {

		_this.markerDB.insert(opt)

	}
	//存储polyline
	_this.savePolylineToDB = function(opt) {

		_this.polylineDB.insert(opt)

	}
	//获取线上所有点
	_this.getMarkerFormDB = function(opt) {
		// var opt = $.extend({
		// type : _this.config.action.path
		// }, opt || {});
		return _this.markerDB(opt || {})
	}
	//将点与线的关联记录下

	_this.saveMarkerBelongToPolyline = function(mdb, lineid) {

		mdb.first().be.push({
			line : lineid,
			index : null
		})

	}
	//将线与线关联起来

	_this.saveLineBelongToLine = function(linedb, lineid) {

		linedb.first().be.push(lineid)

	}
	//获取轨迹上第一个点
	_this.getFirstPathMarkerFormDB = function() {

		return _this.getMarkerFormDB({
			type : _this.config.action.path
		}).first()

	}
	//获取轨迹上第一个点坐标
	_this.getFirstPathMarkerPosition = function() {
		return _this.getFirstPathMarkerFormDB().obj.getPosition()
	}
	//获取轨迹上最后一个点
	_this.getLastPathMarkerFormDB = function() {
		return _this.getMarkerFormDB({
			type : _this.config.action.path
		}).last()
	}
	//获取线路

	_this.getPolylineFormDB = function(opt) {

		return _this.polylineDB(opt || {})

	}
	//获取轨迹线
	_this.getDrawPathFormDB = function() {
		return _this.polylineDB({
			type : _this.config.action.path
		})
	}
	/*********************************************************************************************************/
	//如果创建轨迹点时选择的是已有的marker,将所选marker存储到临时数据库

	_this.saveMarkerToTemDB = function(obj) {

		_this.temMarkerDB.insert(obj)

	}
	//删除所有临时存储的marker
	_this.delMarkerFormTemDB = function() {

		_this.temMarkerDB().remove()

	}
	//获取所有临时存储marker
	_this.getMarkerFormTemDB = function(opt) {

		return _this.temMarkerDB(opt || {})

	}
	/*********************************************************************************************************/
	//如果创建轨迹点时选择的是已有的polyline,将所选polyline存储到临时数据库

	_this.savePolylineToTemDB = function(obj) {

		_this.temPolylineDB.insert(obj)

	}
	//删除所有临时存储的marker
	_this.delPolylineFormTemDB = function() {

		_this.temPolylineDB().remove()

	}
	//获取所有临时存储marker
	_this.getPolylineFormTemDB = function(opt) {

		return _this.temPolylineDB(opt || {})

	}
	/*********************************************************************************************************/

	//绘制设备时，如果轨迹在marker上，则将选中marker与线做关联

	_this.bindSelectMarkerTopolyline = function(lineObj) {

		var pathMarkersDB = _this.getMarkerFormDB({
			type : _this.config.action.path
		})

		pathMarkersDB.each(function(r, i) {

			if (_this.getMarkerFormTemDB({
				index : r.be[0].index
			}).count() != 0) {//该轨迹点在设备上
				var _id = _this.getMarkerFormTemDB({
					index : r.be[0].index
				}).first().id, _markerDB = _this.getMarkerFormDB({
					id : _id
				});

				_this.saveMarkerBelongToPolyline(_markerDB, lineObj.__gm_id)
			}

		})
	}
	/**************************************************************************************************************************/

	//设定绘图动作
	_this.setDrawAction = function(ac) {
		//改变鼠标指针
		if (ac == _this.config.action.path) {
			_this.setMapCursor("crosshair")
		} else {
			_this.removeMapCursor()
		}

		_this.action = ac;

		return _this;

	}
	//获取当前绘图动作
	_this.getDrawAction = function() {

		return _this.action;

	}
	//设置鼠标指针样式
	_this.setMapCursor = function(c) {

		$(_this.map.getDiv()).find("div").addClass(c)

	}
	//删除鼠标样式
	_this.removeMapCursor = function() {

		$(_this.map.getDiv()).find("div").removeClass("crosshair")

	}
	//删除轨迹,并且清除轨迹点
	_this.delDrawPath = function() {

		if (_this.getDrawPathFormDB().count() == 0) {

			return;
		}

		var markers = _this.getMarkerFormDB({
			type : _this.config.action.path
		}), polylines = _this.getDrawPathFormDB().first();

		markers.each(function(o, i) {
			_this.delMarker(o.obj, o.obj.__gm_id)
		})

		_this.delPolyline(polylines.obj, polylines.obj.__gm_id)

		_this.delMarkerFormTemDB()
		_this.delPolylineFormTemDB()

	}
	//删除点 ，删除点以后去清空数据库
	_this.delMarker = function(m, id) {
		_this.mgr.removeMarker(m)
		m.setMap(null);
		_this.getMarkerFormDB({
			id : id
		}).remove()
	}
	//删除线
	_this.delPolyline = function(l, id) {
		l.setMap(null);
		_this.getDrawPathFormDB().remove()
	}
	//获取两点之间连线中点
	//利用google map geometry Library
	//返回点 latLng
	_this.findMiddleFor2Point = function(point1, point2) {
		var distance = google.maps.geometry.spherical.computeDistanceBetween(point1, point2), heading = google.maps.geometry.spherical.computeHeading(point1, point2), point = google.maps.geometry.spherical.computeOffset(point1, distance / 80, heading);
		return point;
	}
	/**************************************************************************************************************************/
	//创建Marker
	_this.createMarker = function(opt, callback, polyline) {

		var marker = new GM.Marker(opt || {});
		marker.__gm_id = opt.id ? opt.id : "m_" + DM.getOnlyID();
		//marker.setMap(_this.map);
		_this.mgr.addMarker(marker, 17);
		//_this.mgr.refresh();
		_this.markerEvent(marker);

		/*************************将所创建marker存入DB****************************/

		_this.saveMarkerToDB({
			id : marker.__gm_id,
			type : opt.type ? _this.config.action[opt.type] : null,
			obj : marker,
			be : [{
				line : opt.line ? opt.line : null,
				index : opt.index ? opt.index : null
			}]
		})

		/*******************************************************/

		if (opt.label) {

			var label = new MapLabel({
				text : opt.label,
				position : marker.getPosition(),
				fontSize : 24,
				align : 'center',
				map : _this.map
			});
			label.bindTo('position', marker);
			marker.label = opt.label;
		}

		if (polyline) {
			_this.bindMarkerToPolyline(marker, polyline)
		}

		/**********************************************************/

		GMEVENT.addListener(marker, "dragstart", function(e) {

			_this.dragMarkerStart(this)

		})

		GMEVENT.addListener(marker, "drag", function(e) {

			_this.dragMarker(this)

		})

		callback ? callback(marker) : null;

		return marker;
	}
	//将markder和polyline关联

	_this.bindMarkerToPolyline = function(m, p) {

		var len = p.getPath().getLength();
		//将marker与polyline关联
		m.bindTo('position', p.binder, (len).toString());
	}
	//创建Polyline
	_this.createPolyline = function(opt, callback) {
		var polyline = new GM.Polyline(opt || {});
		polyline.__gm_id = opt.id ? opt.id : "p_" + DM.getOnlyID();
		polyline.binder = new MVCArrayBinder(polyline.getPath());
		polyline.setMap(_this.map);
		callback ? callback(polyline) : null;
		_this.polylineEvent(polyline)
		/*********************************存入DB*****************************************/
		_this.savePolylineToDB({
			id : polyline.__gm_id,
			type : opt.type ? _this.config.action[opt.type] : null,
			obj : polyline,
			name : opt.name ? opt.name : null,
			be : []
		})

		return polyline;
	}
	//向线段里添加点
	_this.pushPositionToPolylinePath = function(polyline, position) {

		var path = polyline.getPath();
		path.push(position);
	}
	//向线段里插入点
	_this.insertPositionIntoPolylinePath = function(polyline, position, index) {

		var path = polyline.getPath();

		path.insertAt(index, position)

	}
	//修改线段坐标
	_this.changePolylinePath = function(polyline, index, position) {
		var path = polyline.getPath();
		path.setAt(index, position);
	}
	//创建Label
	_this.createLabel = function() {

	}
	/**
	 * 判断点是否在折线上
	 * @param {Point} point 点对象
	 * @param {Polyline} polyline 折线对象
	 * @returns {Boolean} 点在折线上返回true,否则返回false
	 */
	_this.isPointOnPolyline = function(point, polyline) {
		//判断点是否在线段上，设点为Q，线段为P1P2 ，
		//判断点Q在该线段上的依据是：( Q - P1 ) × ( P2 - P1 ) = 0，且 Q 在以 P1，P2为对角顶点的矩形内
		var pts = polyline.getPath();
		for (var i = 0; i < pts.length - 1; i++) {
			var curPt = pts.getAt(i);
			var nextPt = pts.getAt(i + 1);
			//首先判断point是否在curPt和nextPt之间，即：此判断该点是否在该线段的外包矩形内
			if (point.lng() >= Math.min(curPt.lng(), nextPt.lng()) && point.lng() <= Math.max(curPt.lng(), nextPt.lng()) && point.lat() >= Math.min(curPt.lat(), nextPt.lat()) && point.lat() <= Math.max(curPt.lat(), nextPt.lat())) {
				//判断点是否在直线上公式
				var precision = (curPt.lng() - point.lng()) * (nextPt.lat() - point.lat()) - (nextPt.lng() - point.lng()) * (curPt.lat() - point.lat());
				if (precision < 2e-10 && precision > -2e-10) {//实质判断是否接近0
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 点击直线，在直线上插入一个点，获取该点位于直线的位置。
	 * @param {Point} point 点对象
	 * @param {Polyline} polyline 折线对象
	 * @returns {Number}  点在直线上返回所在位置，否则不返回
	 */

	_this.getAddPointOnPolylineIndex = function(point, polyline) {

		var pts = polyline.getPath(), plArray = [];

		for (var i = 0; i < pts.length - 1; i++) {

			var curPt = pts.getAt(i);
			var nextPt = pts.getAt(i + 1);

			plArray[i] = new GM.Polyline();

			_this.pushPositionToPolylinePath(plArray[i], curPt)
			_this.pushPositionToPolylinePath(plArray[i], nextPt)

			if (_this.isPointOnPolyline(point, plArray[i])) {

				return i + 1

			}

		}	}
	/**
	 * 获取一条直线上一个点的index
	 * @param {Point} point 点对象
	 * @param {Polyline} polyline 折线对象
	 * @returns {Number}  点在直线上返回所在位置，否则不返回
	 */
	_this.getPointOnPolylineIndex = function(point, polyline) {

		var pts = polyline.getPath();

		for (var i = 0; i < pts.length; i++) {

			if (point == pts.getAt(i)) {

				return i

			}

		}

	}
	/**************************************************************************************************************************/

	//标注移动事件,移动开始时，将与点关联的线段及index存储进markerDB

	_this.dragMarkerStart = function(m) {

		var thisMarkerID = m.__gm_id;

		$(_this.getMarkerFormDB({
			id : thisMarkerID
		}).first().be).each(function(i, r) {

			if (r.line) {
				//修改每个marker所在线上的index
				var polyline = _this.getPolylineFormDB({
					id : r.line
				}).first().obj, index = _this.getPointOnPolylineIndex(m.getPosition(), polyline);
				r.index = index + 1;

			}

		})
	}
	_this.dragMarker = function(m) {

		/*********************************************************/
		//
		//首先找到该点所有线的记录
		/*********************************************************/

		var thisMarkerID = m.__gm_id;

		$(_this.getMarkerFormDB({
			id : thisMarkerID
		}).first().be).each(function(i, r) {

			if (r.line) {

				var polyline = _this.getPolylineFormDB({
					id : r.line
				}).first().obj, index = r.index;

				_this.changePolylinePath(polyline, index - 1, m.getPosition())

			}

		})
	}
	/**************************************************************************************************************************/

	//绘制轨迹点
	_this.drawPath = function(e, mObj, type) {

		var polyline, marker, index, path;
		index = _this.getMarkerFormDB({
			type : _this.config.action.path
		}).count();

		if (_this.getDrawPathFormDB().count() == 0) {//存储polyline

			polyline = _this.createPolyline($.extend(_this.config.polylineOpt.path, {
				type : _this.config.action.path
			}));

		} else {
			polyline = _this.getDrawPathFormDB().first().obj;

			_this.getLastPathMarkerFormDB().obj.setIcon(_this.config.markersImages.pathPoint);
		}
		marker = _this.createMarker({
			position : e.latLng,
			draggable : true,
			type : "path",
			line : polyline.__gm_id,
			index : index + 1,
			icon : _this.config.markersImages.pathPointSelect
		}, function(m) {

			m.set("title", m.__gm_id)
		}, polyline);
		_this.pushPositionToPolylinePath(polyline, e.latLng)

		//如果创建轨迹点时选择的是已有的marker,将所选marker存储到临时数据库

		if (mObj && type == "m") {

			_this.saveMarkerToTemDB({
				id : mObj.__gm_id,
				index : index + 1,
				obj : mObj
			})

		} else if (mObj && type == "p") {

			_this.savePolylineToTemDB({

				id : mObj.__gm_id,
				index : index + 1,
				obj : mObj

			})

		}

	}
	//绘制单点设备
	_this.drawDevice = function(type, position, id, name) {

		_this.setDrawAction(_this.config.action[type]);

		//在地图上创建新Marker
		var newMarker = _this.createMarker({
			position : position,
			icon : _this.config.markersImages[type],
			draggable : true,
			id : "m_" + id,
			title : "m_" + id,
			label : name,
			type : _this.config.action[type]
		}, function(m) {

			//创建完成后将轨迹删除
			_this.delDrawPath()
		})
	}
	//绘制线路
	//type 类型  path 路径 id name
	_this.drawPolyline = function(type, opt) {

		var newPolyline = _this.createPolyline($.extend(_this.config.polylineOpt[type], opt || {}))

		opt.path ? newPolyline.setPath(opt.path) : null;

		return newPolyline;
	}
	//检测是否可以添加设备
	_this.checkPathRule = function(callback) {
		if (_this.getMarkerFormDB({
			type : _this.config.action.path
		}).count() == 0) {//没有轨迹点不允许添加marker
			alert("请先添加轨迹点")
			return false;
		}

		if (_this.getMarkerFormTemDB().count() != 0) {//如果轨迹路线上已经有设备占用，也不允许添加marker

			alert("轨迹上已有相关设备，请重新选择！")
			return false
		}

		callback()

	}
	//检测是否可以轨迹沿布
	_this.checkAroundPathRule = function(callback) {

		_this.setDrawAction(_this.config.action.around)

		if (_this.getMarkerFormDB({
			type : _this.config.action.path
		}).count() == 0) {//没有轨迹点不允许添加marker
			alert("请先添加轨迹点")
			return false;
		} else if (_this.getMarkerFormDB({
			type : _this.config.action.path
		}).count() == 1) {
			alert("不符合布线规则")
			return false;
		}

		callback()

	}
	//围绕轨迹点绘制设备,传入需要绘制的设备类型及起始号数
	//hasMarker true/false 是否需要添加marker
	//markerType 设备类型
	//polylineType 线类型
	//index marker起始编号
	_this.drawDeviceAroundPath = function(markerType, polylineType, index) {

		var pathMarkersDB = _this.getMarkerFormDB({
			type : _this.config.action.path
		}), pathLineDB = _this.getDrawPathFormDB(), temMarkerDB = _this.getMarkerFormTemDB();

		var newPolyline = _this.drawPolyline(_this.config.action[polylineType], {
			type : _this.config.action[polylineType],
			path : _this.getDrawPathFormDB().first().obj.getPath()
		});

		pathMarkersDB.each(function(r, i) {

			var pathMarker = r.obj;

			if (_this.getMarkerFormTemDB({
				index : r.be[0].index
			}).count() != 0) {//该轨迹点在设备上

				var _id = _this.getMarkerFormTemDB({
					index : r.be[0].index
				}).first().id, _markerDB = _this.getMarkerFormDB({
					id : _id
				});
				_this.saveMarkerBelongToPolyline(_markerDB, newPolyline.__gm_id)

			} else {

				var marker = _this.createMarker({
					position : pathMarker.getPosition(),
					draggable : true,
					label : index + i + 1,
					icon : _this.config.markersImages[markerType],
					line : newPolyline.__gm_id,
					index : i + 1,
					type : _this.config.action[markerType]
				}, function(m) {
					/**
					 * ***************************
					 */
					console.log(m.__gm_id)

					m.set("title", m.__gm_id)
				});

				if (_this.getPolylineFormTemDB({

					index : r.be[0].index

				}).count() != 0) {

					//该轨迹点在线上,找到该点位置，并在该位置给线添加一个point
					var _temPolyline = _this.getPolylineFormTemDB({
						index : r.be[0].index
					}).first().obj, _index = _this.getAddPointOnPolylineIndex(pathMarker.getPosition(), _temPolyline), _markerDB = _this.getMarkerFormDB({
						id : marker.__gm_id
					});

					_this.insertPositionIntoPolylinePath(_temPolyline, pathMarker.getPosition(), _index)
					_this.saveMarkerBelongToPolyline(_markerDB, _temPolyline.__gm_id)

				}

			}

		})
		_this.delDrawPath()
	}
	//绘制电缆,电缆由2条辅助线，2个电缆头，1条电缆构成
	//设备及线路类型
	_this.drawDeviceDL = function(name, id, path) {

		var pathMarkersDB = _this.getMarkerFormDB({
			type : _this.config.action.path
		}), pathLineDB = _this.getDrawPathFormDB(), temMarkerDB = _this.getMarkerFormTemDB();

		var newPolyline = _this.drawPolyline(_this.config.action.dl, {
			type : _this.config.action.dl,
			id : id,
			name : name,
			path : path
		});

		var _path = newPolyline.getPath(), _pathSize = _path.getLength(), _newfirst = _this.findMiddleFor2Point(_path.getAt(0), _path.getAt(1)), _newLast = _this.findMiddleFor2Point(_path.getAt(_pathSize - 1), _path.getAt(_pathSize - 2));

		var dlt1 = _this.createMarker({//绘制电缆头
			position : _newfirst,
			draggable : true,
			icon : _this.config.markersImages.dlt,
			line : newPolyline.__gm_id,
			index : 1,
			type : _this.config.action.dlt
		}, function(m) {
			//绘制辅助线
			var path1 = new google.maps.MVCArray();
			path1.push(_path.getAt(0));
			path1.push(_newfirst);
			var fzx1 = _this.drawDeviceFZX(path1.getArray());

			_this.saveLineBelongToLine(_this.getPolylineFormDB({
				id : fzx1.__gm_id
			}), newPolyline.__gm_id)

			_this.saveLineBelongToLine(_this.getPolylineFormDB({
				id : newPolyline.__gm_id
			}), fzx1.__gm_id)

			_this.saveMarkerBelongToPolyline(_this.getMarkerFormDB({
				id : m.__gm_id
			}), fzx1.__gm_id)

			if (_this.getMarkerFormTemDB({
				index : 1
			}).count() == 1) {

				_this.saveMarkerBelongToPolyline(_this.getMarkerFormDB({
					id : _this.getMarkerFormTemDB({
						index : 1
					}).first().obj.__gm_id
				}), fzx1.__gm_id)
			}

		});

		var dlt2 = _this.createMarker({//绘制电缆头
			position : _newLast,
			draggable : true,
			icon : _this.config.markersImages.dlt,
			line : newPolyline.__gm_id,
			index : _pathSize,
			type : _this.config.action.dlt
		}, function(m) {
			//绘制辅助线
			var path2 = new google.maps.MVCArray();
			path2.push(_path.getAt(_pathSize - 1));
			path2.push(_newLast);
			var fzx2 = _this.drawDeviceFZX(path2.getArray());

			_this.saveLineBelongToLine(_this.getPolylineFormDB({
				id : fzx2.__gm_id
			}), newPolyline.__gm_id)

			_this.saveLineBelongToLine(_this.getPolylineFormDB({
				id : newPolyline.__gm_id
			}), fzx2.__gm_id)

			_this.saveMarkerBelongToPolyline(_this.getMarkerFormDB({
				id : m.__gm_id
			}), fzx2.__gm_id)

			if (_this.getMarkerFormTemDB({
				index : _pathSize
			}).count() == 1) {

				_this.saveMarkerBelongToPolyline(_this.getMarkerFormDB({
					id : _this.getMarkerFormTemDB({
						index : _pathSize
					}).first().obj.__gm_id
				}), fzx2.__gm_id)

			}

		});

		_path.setAt(0, _newfirst);
		_path.setAt(_pathSize - 1, _newLast);

		_this.delDrawPath()
	}
	//绘制辅助线
	_this.drawDeviceFZX = function(path, id, autobind) {

		var fzx = _this.drawPolyline(_this.config.action.fzx, {
			type : _this.config.action.fzx,
			id : id,
			path : path
		});

		if (autobind) {//是否需要将线段与选中点绑定
			_this.bindSelectMarkerTopolyline(fzx)
		}

		return fzx

	}
	/**************************************************************************************************************************/
	//初始化
	that.init = function(mapcontainer) {

		_this.loadMap(mapcontainer);
		_this.mapEvent();

	}

	that.drawPath = function() {//绘制路径

		_this.setDrawAction(_this.config.action.path);

	}

	that.drawKGX = function() {//绘制开关箱

		_this.checkPathRule(function() {

			DM.fun.dialog.open(_this.config.url.kgx, {
				width : 300,
				height : 300,
				onok : function(cw) {
					_this.drawDevice(_this.config.action.kgx, _this.getFirstPathMarkerPosition(), cw.id, cw.name)
				}
			})
		})
	}

	that.drawFJX = function() {//绘制分接箱

		_this.checkPathRule(function() {
	
			DM.fun.dialog.open(_this.config.url.fjx, {
				width : 300,
				height : 300,
				onok : function(cw) {
					_this.drawDevice(_this.config.action.fjx, _this.getFirstPathMarkerPosition(), cw.id, cw.name)
				}
			})
			
			
		})
	}

	that.drawJKX = function() {//绘制架空线

		_this.checkAroundPathRule(function(temMarkerDB, path) {
			
			
			DM.fun.dialog.open(_this.config.url.jkx, {
				width : 300,
				height : 300,
				onok : function(cw) {
					_this.drawDeviceAroundPath(cw.type, "jkx", cw.num)
				}
			})

		})
	}

	that.drawDL = function() {//绘制电缆

		_this.checkAroundPathRule(function() {		
			DM.fun.dialog.open(_this.config.url.dl, {
				width : 300,
				height : 300,
				onok : function(cw) {
					_this.drawDeviceDL(cw.name, cw.id, _this.getDrawPathFormDB().first().obj.getPath())
				}
			})			
		})
	}

	that.drawFZX = function() {//绘制辅助线

		_this.checkAroundPathRule(function() {
			_this.drawDeviceFZX(_this.getDrawPathFormDB().first().obj.getPath(), null, true)
			_this.delDrawPath()

		})
	}
	//清空轨迹
	that.delPath = function() {
		_this.delDrawPath()
	}
	/*************************************************************************************/

	that.getAllMarkerFormDB = function() {

		console.log(_this.getMarkerFormDB().get())

		return _this.getMarkerFormDB().get()

	}

	that.getAllMarkerFormTemDB = function() {

		console.log(_this.getMarkerFormTemDB().get())

	}

	that.getAllPolylineFormTemDB = function() {

		console.log(_this.getPolylineFormTemDB().get())

	}

	that.getPolylineFormDB = function() {
		console.log(_this.getPolylineFormDB().get())
	}
	/*************************************************************************************/
	return that;

}